import React, { useRef, useState, useEffect } from 'react';
import Cropper from 'react-cropper';
import 'cropperjs/dist/cropper.css';
import './index.css';
import { UploadOutlined } from '@ant-design/icons';
import { Upload, Button, Space, Divider, Modal, Select } from 'antd';

const { Option } = Select;

function CropperComponent(props) {
    const cropperRef = useRef(null);
    const [imgsrc, setImgsrc] = useState(null);
    const { img } = props;
    const [image, setImage] = useState(null);
    const [downloadOptions, setDownloadOptions] = useState({ size: '300x200', type: 'jpeg' });
    const [isModalVisible, setIsModalVisible] = useState(false);

    useEffect(() => {
        if (img) {
            setImage(img);
        }
    }, [img]);

    const handleCrop = () => {
        const imageElement = cropperRef.current;
        const cropper = imageElement?.cropper;
        const back64Cropper = cropper.getCroppedCanvas().toDataURL();
        console.log(cropper.getCroppedCanvas().toDataURL("image/jpeg"), "裁剪的base64编码");
        const base64Data = back64Cropper;
        const url = base64ToUrl(base64Data);
        console.log("剪切url=", url);
        setImgsrc(url);
    };

    function base64ToUrl(base64Data) {
        const blob = base64ToBlob(base64Data);
        const url = URL.createObjectURL(blob);
        return url;
    }

    function base64ToBlob(base64Data) {
        const byteString = atob(base64Data.split(',')[1]);
        const mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
        const ab = new ArrayBuffer(byteString.length);
        const ia = new Uint8Array(ab);
        for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        return new Blob([ab], { type: mimeString });
    }

    const replaceImg = (img) => {
        const reader = new FileReader();
        reader.readAsDataURL(img.file.originFileObj);
        reader.onload = ({ target: { result } = {} }) => {
            setImage(result);
        };
        return false;
    };

    const showDownloadModal = () => {
        setIsModalVisible(true);
    };

    const handleDownload = () => {
        const { size, type } = downloadOptions;
        if (!imgsrc) return;

        const link = document.createElement('a');
        link.href = imgsrc; 
        link.download = `cropped-image.${type}`; 
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        setIsModalVisible(false); // Close the modal after downloading
    };

    return (
        <div className='copy'>
            <Cropper
                ref={cropperRef}
                src={image}
                style={{ height: '400px', width: '200px' }}
            />
            <div className='copy-but'>
                <Space>
                    <Upload fileList={[]} onChange={replaceImg} accept="image/*">
                        <Button size='large' className="upload" icon={<UploadOutlined />}>
                            选择图片
                        </Button>
                    </Upload>
                    <Button size='large' className="button" type="primary" onClick={handleCrop}>
                        确定裁剪
                    </Button>
                    <Button size='large' className="button" type="default" onClick={showDownloadModal} disabled={!imgsrc}>
                        下载裁剪的图片
                    </Button>
                </Space>
            </div>
            <div className='copy-img'>
                <Divider plain>裁剪好的图片</Divider>
                <div style={{ height: "200px", width: "300px", border: "1px solid #ccc", display: "flex", justifyContent: "center", alignItems: "center" }}>
                    <img style={{ width: "100%", height: '100%' }} src={imgsrc} alt="Cropped" />
                </div>
            </div>

            <Modal
                title="下载设置"
                visible={isModalVisible}
                onOk={handleDownload}
                onCancel={() => setIsModalVisible(false)}
            >
                <div>
                    <label htmlFor="size">选择图片尺寸:</label>
                    <Select
                        id="size"
                        defaultValue="300x200"
                        style={{ width: 120 }}
                        onChange={(value) => setDownloadOptions({ ...downloadOptions, size: value })}
                    >
                        <Option value="300x200">300x200</Option>
                        <Option value="600x400">600x400</Option>
                        <Option value="1200x800">1200x800</Option>
                    </Select>
                </div>
                <div style={{ marginTop: 16 }}>
                    <label htmlFor="type">选择图片类型:</label>
                    <Select
                        id="type"
                        defaultValue="jpeg"
                        style={{ width: 120 }}
                        onChange={(value) => setDownloadOptions({ ...downloadOptions, type: value })}
                    >
                        <Option value="jpeg">JPEG</Option>
                        <Option value="png">PNG</Option>
                    </Select>
                </div>
            </Modal>
        </div>
    );
}

export default CropperComponent;
